<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../public/css/bootstrap.min.css">
    <title>Document</title>
    <style>
        /* ul li{
            background-color: #faf;
        } */
        body{
            position: relative;
            padding-top: 50px;
        }
        .border{
            border: 1px solid rgb(187, 187, 187);
        }
        .mypic>div>img{
            max-height: 200px;
            margin: 0 auto;
        }
        .userpic{
            max-height: 10%;
            width: auto;
            border: 1px dotted rgb(187, 187, 187);
        }
        div{
            box-sizing: border-box;
        }
        .both:after{
            content: "";
            display: table;
            clear: both;
        }
        .div_pinglun{
            position: absolute;
            width: 100%;
            height: 100%;
        }
        .btn_pinglun{
            position: absolute;
            left: 50%;
            top: 35%;
            transform: translate(-50%, -50%);
        }
    </style>    
</head>
<body>
    <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container-fluid  col-lg-8 col-lg-offset-2 col-md-8 col-md-offset-2">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">欢迎来到ZZQ的微博</a>
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-right">
                    <% if(login){ %>
                        <li data-login="<%= login %>"><a id='username' data-login="<%= login %>"><%= user %></a></li>
                    <% }else{ %>
                        <li data-login="<%= login %>"><a href="http://localhost:3000/login" id='username' data-login="<%= login %>">登录</a></li>
                    <% } %>
                    <li><a href="http://localhost:3000/chatroom">聊天室</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">设置 <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">个人信息</a></li>
                            <li><a href="#">主页</a></li>
                            <li><a href="http://localhost:3000/updatepassword">修改密码</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="http://localhost:3000/quit">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>
        <!--轮播图-->
    <div class="container col-lg-12">
        <div class="col-lg-6 col-lg-offset-3 col-md-8 col-md-offset-2"style="padding: 0;">
                <div class=" col-lg-4 col-md-4  col-xs-12"style="padding: 0;">
                    <div id='myCarousel' class="carousel slide" data-ride='carousel'>
                        <ol class="carousel-indicators">
                            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                            <li data-target="#myCarousel" data-slide-to="1"></li>
                            <li data-target="#myCarousel" data-slide-to="2"></li>
                            <li data-target="#myCarousel" data-slide-to="3"></li>
                            <li data-target="#myCarousel" data-slide-to="4"></li>
                        </ol>
                        <div class="carousel-inner mypic" style="background-color: rgb(182, 182, 182);"> 
                            <div class='item active'>
                                <img src="../public/img/1.jpg" alt="">
                            </div>
                            <div class='item'>
                                <img src="../public/img/2.jpg" alt="">
                            </div>
                            <div class='item'>
                                <img src="../public/img/3.jpg" alt="">
                            </div>
                            <div class='item'>
                                <img src="../public/img/4.jpg" alt="">
                            </div>
                            <div class='item'>
                                <img src="../public/img/5.jpg" alt="">
                            </div>
                        </div>
                        <a href="#myCarousel" data-slide="prev" class='left carousel-control'>
                            <span class="icon-prev"></span>
                        </a>
                        <a href="#myCarousel" data-slide="next" class='right carousel-control'>
                            <span class="icon-next"></span>
                        </a>
                    </div>
                </div>
                <p class='col-lg-8 col-md-8  col-xs-12 text-center' style="line-height: 200px;margin: 0;background-color: rgb(182, 182, 182); font-weight: 900;font-size:30px;">Hello, my friends!</p>
        </div>
    </div>

    
    <!--评论模拟框按钮 -->
    <!-- <div style="display: none;">
        <button type="button" class="btn btn-success" data-toggle='modal'   id="btn_pinglun2"></button>
    </div> -->
    <!--评论失败模拟框 -->
    <div class='modal fade' id="myModal" >
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class='close' data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title">温馨提示</h4>
                </div>
                <div class="modal-body">
                    登录后可进行操作,确定要登录吗？
                </div>
                <div class="modal-footer">
                    <a type="button" class="btn btn-primary" href="http://localhost:3000/login">登录</a>
                    <button type="button" class="btn btn-primary" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>
    <div class="container col-lg-12">
        <div class="col-lg-6 col-lg-offset-3 col-md-8 col-md-offset-2" style="padding:0">           
            <div class="panel-group" id='myGroup'>
                <% for(var i=0;i<mess.length;i++){ %>
                    <div class='panel panel-default' style="margin-bottom: 30px;">
                        <li class="list-group-item" style="border: 0;" >
                            <div class="media">
                                <div class="media-left">
                                    <img class="media-object img-circle userpic" src="../public/img/1.jpg" alt="">
                                </div>
                                <div class="media-body">
                                    <h4 class="media-heading"><%= mess[i].username %>
                                    </h4>
                                    <h6 class="mytimes"><%= mess[i].time %></h6>
                                    <hr style="border:1 dashed #987cb9;margin-top: 0;" width="100%" >
                                    <div data-uid="<%= mess[i]._id %>">
                                        <%= mess[i].weibo %>
                                    </div>
                                </div>
                                <hr style="border:1 dashed #987cb9;margin-bottom: 0;" width="100%" >
                            </div>
                        </li>
                        <div class="collapse" id="collapse<%= i %>">
                            <div class="panel-body" style="padding-bottom: 0;">
                                <li class="list-group-item" style="border: 0;padding-bottom: 0;">
                                    <textarea class="form-control" rows="2" style="resize: none;"></textarea>
                                    <button type="button" class="btn btn-info comment" data-comment="<%= mess[i]._id %>" style="margin-bottom:10px">评论</button>
                                    <div id="<%= mess[i]._id %>"></div>                             
                                </li>
                            </div>
                        </div>    
                        <div class="panel-heading both" style='background-color: white;'>
                            <a class="btn btn-primary getlove" style="text-shadow: black 2px 2px 2px;float: right;" data-comment="<%= mess[i]._id %>"><span class="glyphicon glyphicon-heart-empty"></span> <span style="font-size:16px">0</span></a>
                            <a class="btn btn-primary getcomment" href="#collapse<%= i %>" data-toggle="collapse" data-parent='#myGroup' style="text-shadow: black 2px 2px 2px;float: right;margin-right: 10px;" data-comment="<%= mess[i]._id %>">评论 <span style="font-size:16px">0</span></a>
                            <!-- class="badge" -->                            
                        </div>
                    </div>
                <% } %>
            </div>
            <nav>
                <ul class="pagination" id="page">
                </ul>
            </nav>
            <div style="position: relative;">
                <% if(!login){ %> 
                    <div class="div_pinglun">
                        <a class="btn btn-warning btn_pinglun" href="http://localhost:3000/login">
                            请登录后发布微博
                        </a>
                    </div>
                <% }%>
                <textarea class="form-control" id="mytext"  rows="4" style="resize: none;"></textarea>
                <button type="button" class="btn btn-info" id="sendweibo">发布</button>
            </div>
        </div>
        <!-- <ul class="list-unstyled text-center col-lg-12 col-md-12">
            <li class="col-lg-3">
                <h1>标题</h1>
            </li>
            <li class="col-lg-3">
                <h1>标题</h1>
            </li>
            <li class="col-lg-3">
                <h1>标题</h1>
            </li>
            <li class="col-lg-3">
                <h1>标题</h1>
            </li>
        </ul> -->
        
    </div>
    <script src="../public/js/jquery.js"></script>
    <script src="../public/js/bootstrap.min.js"></script>
    <script>
        function isNull( str ){//判断是否为空
            if ( str == "" ) return true;
            var regu = "^[ ]+$";
            var re = new RegExp(regu);
            return re.test(str);
        }
        //发布微博
        $('#sendweibo').click(function(){
            let weibo=$(this).prev().val()
            let username=$('#username').html()
            if($('#username').attr('data-login')!="true"){
                $('#myModal').modal({
                    "target":'#myModal'
                })
            }else if(isNull(weibo)){ 
                alert('不能为空'); 
            }else{
                $.ajax({
                    url:'http://localhost:3000/weibo',
                    type:'post',
                    dataType:"json",
                    data:{
                        'username':username,
                        'weibo':weibo
                    },
                    error:()=>{
                        console.log('微博发布失败')
                    },
                    success:(res)=>{
                        $('#mytext').val('');
                        $.ajax({//渲染分页按钮
                            url:'http://localhost:3000/getweibo',
                            type:'get',
                            error:()=>{console.log(error)},
                            success:(res)=>{
                                bindpage(Math.ceil(res.mess.length/5),1)
                            }
                        })
                    }
                })
            }            
        })
        //发布评论
        function bindcomment(){
            $('.comment').click(function(){
                console.log($('#username').attr('data-login'))
                let pinglun=$(this).prev().val()
                let id=$(this).attr('data-comment')
                let username=$('#username').html()
                if($('#username').attr('data-login')!="true"){
                    $('#myModal').modal({
                        "target":'#myModal'
                    })
                }else if(isNull(pinglun)){ 
                    alert('不能为空'); 
                }else{
                    $.ajax({
                        url:'http://localhost:3000/comment',
                        type:'post',
                        dataType:"json",
                        data:{
                            'username':username,
                            'weibo':pinglun,
                            'id':id
                        },
                        error:()=>{
                            console.log('评论发布失败')
                        },
                        success:(res)=>{
                            console.log('发送成功')
                            console.log(res)
                            $(this).prev().val('')
                            // $(this).parent().parent().next().children()[1].click
                            let id=$(this).attr('data-comment')
                            if(prev_id!=0){
                                $(`#${prev_id}`).empty();
                            }
                            $.ajax({
                                url:'http://localhost:3000/getcomment',
                                type:'post',
                                dataType:"json",
                                data:{
                                    'uid':id,
                                    'n':5
                                },
                                error:()=>{
                                    console.log('评论获取失败')
                                },
                                success:(res)=>{   
                                    if(res.length>0){
                                        $(`#${id}`).append(`<ul class="list-group" style="border:0;">
                                        <li class="list-group-item"> `);   
                                        for (let i=0;i<res.length;i++){
                                            $(`#${res[i].uid}>ul>li`).append(comment_1(res[i]))
                                        }
                                        let length=parseInt($($(this)[0].getElementsByTagName('span')).html());
                                        if(res.length<length){
                                            $(`#${id}>ul>li`).append(`<div class='list-group-item list-group-item-success text-center' id='manycomments'>展开更多评论<span class='caret'></span></div>`)
                                        } 
                                        let length1=$(`#${id}>ul>li>.media`).length;
                                        getcomments2(id,length1,length)  
                                        gettimess()
                                    }
                                    prev_id=id
                                }
                            })
                            getcomment()
                        }
                    })
                }        
            })
        }
        bindcomment()
        //获取评论数
        function getcomment(){
            let getcomment=$('.getcomment')
            for(let i=0;i<getcomment.length;i++){
                let id=$(getcomment[i]).attr('data-comment')
                $.ajax({
                    url:'http://localhost:3000/getcomment',
                    type:'post',
                    dataType:"json",
                    data:{
                        'uid':id
                    },
                    error:()=>{
                        console.log('评论数发布失败')
                    },
                    success:(res)=>{
                        $($(getcomment[i]).children()[0]).html(res.length)
                    }
                })
            }
        }
        getcomment();
        let prev_id=0//评论开关
        //获取评论
        function getcomments(){
            $('.getcomment').click(function(){
                let id=$(this).attr('data-comment')
                if(prev_id!=0){
                    $(`#${prev_id}`).empty();
                }
                $.ajax({
                    url:'http://localhost:3000/getcomment',
                    type:'post',
                    dataType:"json",
                    data:{
                        'uid':id,
                        'n':5
                    },
                    error:()=>{
                        console.log('评论获取失败')
                    },
                    success:(res)=>{   
                        if(res.length>0){
                            $(`#${id}`).append(`<ul class="list-group" style="border:0;">
                            <li class="list-group-item"> `);   
                            for (let i=0;i<res.length;i++){
                                $(`#${res[i].uid}>ul>li`).append(comment_1(res[i]))
                            }
                            let length=parseInt($($(this)[0].getElementsByTagName('span')).html());
                            if(res.length<length){
                                $(`#${id}>ul>li`).append(`<div class='list-group-item list-group-item-success text-center' id='manycomments'>展开更多评论<span class='caret'></span></div>`)
                            } 
                            let length1=$(`#${id}>ul>li>.media`).length;
                            getcomments2(id,length1,length)  
                            gettimess()
                        }
                        prev_id=id
                    }
                })
            })
        }
        getcomments()
        
        //获取更多评论
        function getcomments2(id,length,length2){
            $('#manycomments').click(function(){
                $(this).remove()
                $.ajax({
                    url:'http://localhost:3000/getcomment',
                    type:'post',
                    dataType:"json",
                    data:{
                        'uid':id,
                        'm':length,
                        'n':5
                    },
                    error:()=>{
                        console.log('评论获取失败')
                    },success:(res)=>{
                        for (let i=0;i<res.length;i++){
                            $(`#${res[i].uid}>ul>li`).append(comment_1(res[i]))
                        }
                        if(length+res.length<length2){
                            $(`#${id}>ul>li`).append(`<div class='list-group-item list-group-item-success text-center' id='manycomments'>展开更多评论<span class='caret'></span></div>`)
                            let length1=$(`#${id}>ul>li>.media`).length;
                            getcomments2(id,length1,length2)
                        }
                        gettimess()
                    }
                })
            })
        }
        function comment_1(i){
            return `<div class="media">
                        <div class="media-left">
                            <img class="media-object img-circle userpic" src="../public/img/1.jpg" alt="">
                        </div>
                        <div class="media-body">
                            <div class="media-heading">
                                <div>${i.mess.username}</div>
                                <div>${i.mess.weibo}</div> 
                            </div>
                            <h6 class="mytimess" style="margin:5px 0">
                                ${i.mess.time}
                            </h6>
                            <hr style="border:1 dashed #987cb9;margin-top: 0;" width="100%" >
                        </div>
                    </div>`
        }

        function html(mess,i){//分页内容
            return `<div class='panel panel-default' style="margin-bottom: 30px;">
            <li class="list-group-item" style="border: 0;" >
                <div class="media">
                    <div class="media-left">
                        <img class="media-object img-circle userpic" src="../public/img/1.jpg" alt="">
                    </div>
                    <div class="media-body">
                        <h4 class="media-heading">${mess[i].username}
                        </h4>
                        <h6 class='mytimes'>${mess[i].time }</h6>
                        <hr style="border:1 dashed #987cb9;margin-top: 0;" width="100%" >
                        <div data-uid="${ mess[i]._id }">
                            ${ mess[i].weibo }
                        </div>
                    </div>
                    <hr style="border:1 dashed #987cb9;margin-bottom: 0;" width="100%" >
                </div>
            </li>
            <div class="collapse" id="collapse${ i }">
                <div class="panel-body" style="padding-bottom: 0;">
                    <li class="list-group-item" style="border: 0;padding-bottom: 0;">
                        <textarea class="form-control" rows="2" style="resize: none;"></textarea>
                        <button type="button" class="btn btn-info comment" data-comment="${ mess[i]._id }" style="margin-bottom:10px">评论</button>
                        <div id="${ mess[i]._id }"></div>                             
                    </li>
                </div>
            </div>    
            <div class="panel-heading both" style='background-color: white;'>
                <a class="btn btn-primary getlove" style="text-shadow: black 2px 2px 2px;float: right;"data-comment="${ mess[i]._id }"><span class="glyphicon glyphicon-heart-empty"></span> <span style="font-size:16px">0</span></a>
                <a class="btn btn-primary getcomment" href="#collapse${ i }" data-toggle="collapse" data-parent='#myGroup' style="text-shadow: black 2px 2px 2px;float: right;margin-right: 10px;" data-comment="${ mess[i]._id }">评论 <span style="font-size:16px"></span>                           
                </a>                          
            </div>
        </div> `
        }
        $.ajax({//渲染分页按钮
            url:'http://localhost:3000/getweibo',
            type:'get',
            error:()=>{console.log(error)},
            success:(res)=>{
                bindpage(Math.ceil(res.mess.length/5),1)
            }
        })
        function bind_pagebtn(){
            $('#page>li>span').click(function(){
                $.ajax({//渲染分页按钮
                    url:'http://localhost:3000/getweibo',
                    type:'get',
                    error:()=>{console.log(error)},
                    success:(res)=>{
                        //len 分页长度
                        let len=Math.ceil(res.mess.length/5)
                        let num=parseInt($(this).html())
                        if(isNaN(num)){
                            if($(this).html()=='«'){   
                                let num1=parseInt($('#page>.active>span').html())
                                if(num1>1){
                                    bindpage(len,num1-1)
                                }  
                            }else if($(this).html()=='»'){
                                let num1=parseInt($('#page>.active>span').html())
                                if(num1<len){
                                    bindpage(len,num1+1)
                                }
                            }
                        }else{
                            bindpage(Math.ceil(res.mess.length/5),num)
                        }      
                    }
                })
            })
        }
        function bindpage(len,num){//分页5页
            //len 页码总长 num 页码号
            //分页
            let str=``
            if(len<=5){
                for(let i=1;i<len+1;i++){
                    str+=`<li><span>${i}</span></li>`
                }
            }else{
                if(num<3){
                    for(let i=1;i<6;i++){
                        str+=`<li><span>${i}</span></li>`
                    }
                }else if(num>len-2){
                    for(let i=1;i<6;i++){
                        str+=`<li><span>${len-5+i}</span></li>`
                    }
                }else{
                    for(let i=0;i<5;i++){
                        str+=`<li><span>${num-2+i}</span></li>`
                    }
                } 
            }
            $('#page').empty().append(`<li><span>&laquo;</span></li>${str}<li><span>&raquo;</span></li>`);
            //绑定按钮
            if(len<=5){
                $(`#page>li:eq(${num})`).addClass('active');
            }else{
                if(num<3){
                    $(`#page>li:eq(${num})`).addClass('active');
                }else if(num<len-1){
                    $(`#page>li:eq(3)`).addClass('active');
                }else{
                    $(`#page>li:eq(${-(len-num+2)})`).addClass('active');
                }
            }
            //触发分页
            pages(num*5-5)
            bind_pagebtn()
        }
        function pages(m){//触发分页 m跳过数量
            $.ajax({
                url:`http://localhost:3000/getweibo?m=${m}&n=5`,
                type:'get',
                error:()=>{
                    console.log('微博获取失败')
                },
                success:(res)=>{
                    if(res.mess.length>0){
                        $('#myGroup').empty()
                        for(var i=0;i<res.mess.length;i++){
                            $('#myGroup').append(html(res.mess,i))                  
                        }
                        getcomment()//绑定获取数
                        $("html,body").animate({scrollTop:0},200);
                        // $("html,body").animate({scrollTop:$(document).height()},800);
                        getcomments()//绑定获取评论
                        bindcomment()//绑定发布评论
                        gettimes()//绑定时间
                        //绑定分页按钮 
                        getlove()//点赞
                    }else{} 
                }
            })
        }
        
        
        function gettimes(){
            for(let i=0;i<$('.mytimes').length;i++){//绑定时间
                $($('.mytimes')[i]).html(mytimes(parseInt($($('.mytimes')[i]).html())))
            } 
        }
        function gettimess(){
            for(let i=0;i<$('.mytimess').length;i++){//绑定时间
                if(isNaN($($('.mytimess')[i]).html())){
                    
                }else{
                    $($('.mytimess')[i]).html(mytimes(parseInt($($('.mytimess')[i]).html())))
                } 
            } 
        }
        function mytimes(time){//处理时间
            var nowtime=new Date().getTime();
            var nowyear=new Date().getFullYear();
            var year=new Date(time).getFullYear();
            var month=new Date(time).getMonth()+1;
            var day=new Date(time).getDate();
            var hours=new Date(time).getHours();
            var min=new Date(time).getMinutes();
            hours<10?hours="0"+hours:hours;
            min<10?min="0"+min:min;
            if((nowtime-time)/1000/60<1){
                return `刚刚`
            }else if((nowtime-time)/1000/60/60<1){
                return `${parseInt((nowtime-time)/1000/60)}分钟前`
            }else if((nowtime-time)/1000/60/60<24){
                return `${parseInt((nowtime-time)/1000/60/60)}小时前`
            }else if((nowtime-time)/1000/60/60/24<2){
                return `昨天 ${hours}:${min}`
            }else if(year==nowyear){
                return `${month}-${day} ${hours}:${min}`
            }else{
                return `${year.toString().slice(2)}-${month}-${day} ${hours}:${min}` 
            }
        }
        
        
        function getlove(){
            let getloves=$('.getlove')
            let username=$('#username').html()
            let login=$('#username').attr('data-login')
            for(let i=0;i<getloves.length;i++){
                let id=$(getloves[i]).attr('data-comment')
                $.ajax({
                    url:'http://localhost:3000/dianzan',
                    type:'post',
                    dataType:"json",
                    data:{
                        'username':username,
                        'uid':id,
                        'getlove':1,
                        'login':login
                    },
                    error:()=>{
                        console.log('评论点赞失败')
                    },
                    success:(res)=>{
                        $($(getloves[i]).children()[1]).html(res.len)
                        if(res.love==1){
                            $($(getloves[i]).children()[0]).removeClass('glyphicon-heart-empty').addClass('glyphicon-heart')
                        }else{
                            $($(getloves[i]).children()[0]).removeClass('glyphicon-heart').addClass('glyphicon-heart-empty')
                        }
                    }
                })
                // console.log($(getloves[i]).parent().prev()[0])
                $(getloves[i]).click(function(){
                    if(login=="true"){
                        $.ajax({
                            url:'http://localhost:3000/dianzan',
                            type:'post',
                            dataType:"json",
                            data:{
                                'username':username,
                                'uid':id,
                                'login':login
                            },
                            error:()=>{
                                console.log('评论点赞失败')
                            },
                            success:(res)=>{
                                $($(getloves[i]).children()[1]).html(res.len)
                                if(res.love==1){
                                    $($(getloves[i]).children()[0]).removeClass('glyphicon-heart-empty').addClass('glyphicon-heart')
                                }else{
                                    $($(getloves[i]).children()[0]).removeClass('glyphicon-heart').addClass('glyphicon-heart-empty')
                                }
                            }
                        })
                    }else{
                        $('#myModal').modal({
                            "target":'#myModal'
                        })
                    }  
                })
            }
        }
        
        
    </script>
</body>
</html>
